\chapter{ANALYSIS【分析】}
\thispagestyle{empty}

\section{9.1 Introduction【简介】}
The new analysis category based on g4tools was added in the GEANT4 9.5 release with the aim to provide the users a “light” analysis tool available directly with GEANT4 installation without a need to link their GEANT4 application with an external analysis package. It consists of the analysis manager classes and it includes also the g4tools package.

GEANT4 9.5版本增加了基于g4tools的新分析类，旨在为用户提供一个“轻量级”分析工具，而且该类可直接跟随GEANT4安装而安装，而无需将其GEANT4应用程序与外部分析软件包链接起来。 它由分析管理器类组成，它也包含g4tools包。｛translate by 小二｝

g4tools provides code to write and read histograms and ntuples in several formats: ROOT, XML AIDA format and CSV (comma-separated values format). It is a part of inlib and exlib libraries, that include also other facilities like fitting and plotting.

g4tools提供代码来写和读取多种格式的histograms(直方图)和ntuples(元组)：ROOT，XML AIDA格式和CSV（逗号分隔值格式）。 它是inlib和exlib库的一部分，还包括其他工具，如拟合和绘图。

Since GEANT4 10.4, the output in HDF5 format is also supported, but requires the HDF5 libraries installation as well as GEANT4 libraries built with the -DGEANT4\_USE\_HDF5=ON CMake option.

从GEANT4 10.4版本起，也开始支持HDF5输出的格式，但需要安装HDF5库以及在安装编译的时候使用CMake选项-DGEANT4\_USE\_HDF5 = ON构建的GEANT4库。

The analysis classes provide a uniform, user-friendly interface to g4tools and hide the differences according to a selected output technology from the user. They take care of a higher-level management of the g4tools objects (files, histograms and ntuples), handle allocation and removal of the objects in memory and provide the access methods to them via indexes. They are fully integrated in the GEANT4 framework: they follow GEANT4 coding style and also implement the built-in GEANT4 user interface commands that can be used by users to define or configure their analysis objects.

分析类为g4tools提供统一的，用户友好的界面，并隐藏用户选择的输出技术之间的差异。 他们关注对g4tools对象（文件，直方图和元组对象）进行更高级别的管理，处理内存中对象的分配和删除，并通过索引为它们提供访问方法。 它们完全集成在GEANT4框架中：它们遵循GEANT4编码风格，还实现了内置的GEANT4用户界面命令，用户可以使用它们来定义或配置其分析对象。

An example of use of analysis manager classes is provided in basic example B4, in the B4RunAction and B4EventAction classes.

示例B4提供了使用分析管理器类的示例，代码分布在在B4RunAction和B4EventAction两个文件中。
\section{9.2 Analysis Manager Classes分析管理器类}
The analysis manager classes provide uniform interfaces to the g4tools package and hide the differences between use of g4tools classes for the supported output formats (ROOT, HDF5, AIDA XML and CSV).
An analysis manager class is available for each supported output format:

分析管理器类为g4tools包提供了统一的接口，并隐藏了支持的输出格式（ROOT，HDF5，AIDA XML和CSV）使用g4tools类之间的差异｛translate by 小二｝。

分析管理器类可用于每种支持的输出格式：

•	G4CsvAnalysisManager

•	G4Hdf5AnalysisManager

•	G4RootAnalysisManager

•	G4XmlAnalysisManager

For a simplicity of use, each analysis manager provides the complete access to all interfaced functions though it is implemented via a more complex design.

为了简化使用，每个分析管理器都提供了对所有接口函数的完整访问，尽管它是通过更复杂的设计实现的。

The managers are implemented as singletons. User code will access a pointer to a single instance of the desired manager. The manager has to be created and deleted from the user code. All objects created via analysis manager are deleted automatically with the manager. The concrete types of the analysis manager as well as the handled g4tools objects, are hidden behind a namespace which is selected by including a dedicated include file. This allows the user to use all output technologies in an identical way via these generic types:

管理器实现为singletons。用户代码将访问指向所需管理器的单个实例的指针。 管理器必须从用户代码中创建和删除。 所有通过分析管理器创建的对象都会通过分析管理器自动删除。 分析管理器的具体类型以及处理的g4tools对象都隐藏命名空间后面，该命名空间是通过包含专用的包含文件来选择它。这允许用户通过这些普通类型，以相同的方式使用所有输出技术：

•	G4AnalysisManager: the public analysis interface

•	G4AnaH1[2,3]: one[two,three]-dimensional histogram

•	G4AnaP1[2]: one[two]-dimensional profile

•	G4Ntuple: ntuple

In addition to the G4AnalysisManager functions, a set of GEANT4 UI commands for creating histograms and setting their properties is implemented in associated messenger classes.

除了G4AnalysisManager函数之外，在相关的消息类中也实现了一组用于创建直方图并设置其属性的GEANT4 UI命令。
\subsection{9.2.1 Analysis Manager分析管理器}

To use GEANT4 analysis, an instance of the analysis manager must be created. The analysis manager object is created with the first call to G4AnalysisManager::Instance(), the next calls to this function will just provide the pointer to this analysis manager object. The client code is responsible for deleting the created object what is in our example done in the run action destructor.

要使用GEANT4分析类，必须创建分析管理器的实例。 分析管理器对象是在第一次调用G4AnalysisManager :: Instance()时创建的，接下来对这个函数的调用只提供指向这个分析管理器对象的指针。 用户代码负责删除创建的对象，我们的例子是在run action(这里指的是在RunAction类)的析构函数中完成的。

The example of the code for creating the analysis manager extracted from the basic B4 example is given below:

下面给出的是从B4示例中提取的用于创建分析管理器的代码示例：
\begin{lstlisting}
#include "B4Analysis.hh"
B4RunAction::B4RunAction()
: G4UserRunAction()
{
// Create analysis manager
auto analysisManager = G4AnalysisManager::Instance(); analysisManager->SetVerboseLevel(1);
analysisManager->SetFirstHistoId(1);
}
B4RunAction::~B4RunAction()
{
 delete G4AnalysisManager::Instance();
}
\end{lstlisting}
It is recommended, but not necessary, to create the analysis manager in the user run action constructor and delete it in its destructor. This guarantees correct behavior in multi-threading mode. The code specific to the output format is hidden in B4Analysis.hh where the selection of the output format takes place.

建议（但不是必须）在run action(这里指的是在RunAction类)操作构造函数中创建分析管理器，并在其析构函数中将其删除。 这保证了多线程模式下的正确行为。 特定输出格式的代码隐藏的B4Analysis.hh中，B4Analysis.hh类中决定了选择的输出格式。
\begin{lstlisting}
#ifndef B4Analysis_h
#define B4Analysis_h 1
#include "g4root.hh"
//#include "g4xml.hh"
//#include "g4csv.hh"
//#include "g4hdf5.hh"
#endif
\end{lstlisting}
The level of informative printings can be set by SetVerboseLevel(G4int). Currently the levels from 0 (default) up to 4 are supported.

信息打印的级别可以通过SetVerboseLevel（G4int）来设置。 目前支持从0（默认）到4的级别。
The verbose level can be also set via the UI command:
详细级别也可以通过UI命令设置：
\begin{lstlisting}
/analysis/verbose level
\end{lstlisting}
\subsection{9.2.2 Files handling文件处理}

The analysis manager can handle only one base file at a time. Below we give an example of opening and closing a file extracted from the basic example B4:
分析管理器一次只能处理一个基本文件。 下面我们将根据例子B4，给出一个打开和关闭文件的实例：
\begin{lstlisting}
#include "B4Analysis.hh"
void B4RunAction::BeginOfRunAction(const G4Run* run)
{
// Get analysis manager
 auto analysisManager = G4AnalysisManager::Instance();
// Open an output file
analysisManager->OpenFile("B4");
}
void B4RunAction::EndOfRunAction(const G4Run* aRun)
{
// Save histograms
auto analysisManager = G4AnalysisManager::Instance(); analysisManager->Write();
analysisManager->CloseFile();
}
\end{lstlisting}
The following functions are defined for handling files:
定义了以下函数处理文件：
\begin{lstlisting}
G4bool OpenFile(const G4String& fileName = "");
G4bool Write();
G4bool CloseFile();
\end{lstlisting}

The file name can be defined either directly with OpenFile(const G4String\&) call or separately via SetFileName(const G4String\&) function before calling OpenFile(). It is not possible to change the file name when a file is open and not yet closed. If a file extension is not specified in fileName, it is automatically completed according to a selected output format.

文件名的定义，要么可以直接使用OpenFile（const G4String＆）定义，或者在调用OpenFile()之前，通过SetFileName（const G4String＆）函数定义文件名。 当文件打开并且尚未关闭时，无法更改文件名。 如果文件扩展名未在fileName中指定，则会根据选定的输出格式自动完成。

The file can be optionally structured in sub-directories. Currently only one directory for histograms and/or one directory for ntuples are supported. The directories are created automatically if their names are set to non-empty string values via SetHistoDirectoryName(const G4String\&) and/or SetNtupleDirectoryName(const G4String\&). This setting is ignored with the output formats which do not support this feature (XML, CSV).

该文件可以有选择地在子目录中构建。 目前只支持一个直方图目录和/或一个用于元组的目录。 如果通过SetHistoDirectoryName（const G4String＆）和/或SetNtupleDirectoryName（const G4String＆），并将其名称设置为非空字符串值，则会自动创建目录。 不支持此功能的输出格式（XML，CSV）会忽略此设置。

The following commands for handling files and directories are available

以下用于处理文件和目录的命令可用
\begin{lstlisting}
/analysis/setFileName name	# Set name for the output file
/analysis/setHistoDirName name	# Set name for the histograms directory
/analysis/setNtupleDirName name	# Set name for the histograms directory
\end{lstlisting}
Depending on the selected output format more files can be generated when more than one ntuple is defined in a user application. This is the case of XML and CSV, which do not allow writing more than one ntuple in a file. The ntuple file name is then generated automatically from the base file name and the ntuple name.

根据所选的输出格式，当在用户应用程序中定义多个ntuple时，可以生成更多文件。 对于XML和CSV的情况，它们不允许在一个文件中写入多于一个ntuple。 利用基本文件名和ntuple名称自动生成ntuple文件名。

The analysis manager can handle only one base file at a time, but several base files can be generated successively from GEANT4 session, typically one file is saved per run. A new file can be open only after a previous file was closed. An example of generated more files per session is provided in basic/B5 example and its run2.mac macro. Appending existing files is not supported. When an existing file is open again, its content is overwritten.

分析管理器一次只能处理一个基本文件，但可以从GEANT4session中连续生成几个基本文件，通常每次run只会保存一个文件。 只有在先前文件关闭后才能打开新文件。 在basic / B5示例及其run2.mac宏中提供了每个会话生成更多文件的示例。 不支持追加现有文件。 当现有文件再次打开时，其内容将被覆盖。

\subsection{9.2.3 Histograms}

The code for handling histograms given in the following example is extracted the B4 example classes. In this example, the histograms are created in the run action constructor and they are filled in the end of event.

以下示例中给出的处理直方图的代码是从B4例的类中提取的。 在这个例子中，直方图是在run action的构造函数中创建，它们将在end of event被填充。
\begin{lstlisting}
#include "B4Analysis.hh"
B4RunAction::B4RunAction()
: G4UserRunAction()
{
// Create analysis manager
// ...
// Creating histograms
analysisManager->CreateH1("1","Edep in absorber", 100, 0., 800*MeV); analysisManager->CreateH1("2","Edep in gap", 100, 0., 100*MeV);
}
void B4aEventAction::EndOfEventAction(const G4Run* aRun)
{
// Fill histograms
auto analysisManager = G4AnalysisManager::Instance(); analysisManager->FillH1(1, fEnergyAbs);
analysisManager->FillH1(2, fEnergyGap);
}
\end{lstlisting}
Creating Histograms创建直方图

A one-dimensional (1D) histogram can be created with one of these two G4AnalysisManager functions:
可以使用以下两个G4AnalysisManager函数之一来创建一维（1D）直方图：
\begin{lstlisting}
G4int CreateH1(const G4String& name, const G4String& title,
G4int nbins, G4double xmin, G4double xmax,
const G4String& unitName = "none",
const G4String& fcnName = "none",
const G4String& binSchemeName = "linear");
G4int CreateH1(const G4String& name, const G4String& title,
const std::vector<G4double>& edges,
const G4String& unitName = "none",
const G4String& fcnName = "none");
\end{lstlisting}

where name and title parameters are self-descriptive. The histogram edges can be defined either via the nbins, xmin and xmax parameters (first function) representing the number of bins, the minimum and maximum histogram values, or via the const std::vector<G4double>\& edges parameter (second function) representing the edges defined explicitly. The other parameters in both functions are optional and their meaning is explained in Histograms Properties.

其中名称和标题参数是自描述性的。 直方图的边缘可以通过bin数量，最小值和最大值的nbins，xmin和xmax参数（第一个函数），或者通过const std :: vector <G4double>＆edges参数（第二个函数）定义，代表显式定义的边缘。 两个函数中的其他参数都是可选的，其含义在直方图属性(Histograms Properties)中进行了解释。

Two-dimensional (2D) and three-dimensional (3D) histograms can be created with one of these two functions analogous to those for 1D histograms:

二维（2D）和三维（3D）直方图可以通过以下两种函数之一来创建：类似于一维直方图的函数：
\begin{lstlisting}
G4int CreateH2(const G4String& name, const G4String& title,
G4int nxbins, G4double xmin, G4double xmax,
G4int nybins, G4double ymin, G4double ymax,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& xbinScheme = "linear",
const G4String& ybinScheme = "linear");
G4int CreateH2(const G4String& name, const G4String& title,
const std::vector<G4double>& xedges,
const std::vector<G4double>& yedges,
const G4String& xunitName = "none",
                         const G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none");
G4int CreateH3(const G4String& name, const G4String& title,
G4int nxbins, G4double xmin, G4double xmax,
G4int nybins, G4double ymin, G4double ymax,
G4int nzbins, G4double zmin, G4double zmax,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none",
const G4String& xbinSchemeName = "linear",
const G4String& ybinSchemeName = "linear",
const G4String& zbinSchemeName = "linear");
G4int CreateH3(const G4String& name, const G4String& title,
const std::vector<G4double>& xedges,
const std::vector<G4double>& yedges,
const std::vector<G4double>& zedges,
const G4String& xunitName = "none",
 const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none");
\end{lstlisting}
The meaning of parameters is the same as in the functions for 1D histograms, they are just applied in x, y and z dimensions.

参数的含义与一维直方图的函数中的相同，它们仅对应于x，y和z维度。

The histograms created with G4AnalysisManager get automatically attributed an integer identifier which value is returned from the “Create” function. The default start value is 0 and it is incremented by 1 for each next created histogram. The numbering of 2D and 3D histograms is independent from 1D histograms and so the first created 2D (or 3D) histogram identifier is equal to the start value even when several 1D histograms have been already created.

使用G4AnalysisManager创建的直方图会自动给定一个整数标识符，该标识符是“Create”函数返回的值。 默认的起始值为0，对于每下一个创建的直方图，默认值都会递加1。 二维和三维直方图的编号与一维直方图无关，所以即使已经创建了几个一维直方图，第一个创建的二维（或三维）直方图标识符也等于起始值，默认值也是从0开始。

The start histogram identifier value can be changed either with the SetFirstHistoId(G4int) method, which applies the new value to all histogram types, or with the SetFirstHNId(G4int), where N = 1, 2, 3 methods, which apply the new value only to the relevant histogram type. The first method is demonstrated in the example.

直方图的整数标识符可以被修改，可以使用SetFirstHistoId（G4int）方法将新的值应用于所有直方图类型的或使用SetFirstHNId（G4int）（其中N = 1,2,3）方法来改变起始直方图标识符值，其中应用新值只有相关的(N的三个值对应于1维、二维和三维)直方图类型。 示例中展示了第一种方法。

The histogram names “1”, “2” in the demonstrated example are defined to correspond the histograms identifiers in a similar way as in extended/analysis/AnaEx01 example. This choice is however fully in hands of the user who can prefer longer and more meaningful names.

extended/analysis/AnaEx01示例中的直方图名称“1”，“2”被定义来和对应直方图标识符一样。 然而，这种选择完全掌握在用户手中，用户可以选择更长和更有意义名称的。

All histograms created by G4AnalysisManager are automatically deleted G4AnalysisManager object.
由G4AnalysisManager创建的所有直方图都会自动删除G4AnalysisManager对象。

Histograms can be also created via UI commands. The commands to create 1D histogram:
直方图也可以通过UI命令创建。 创建一维直方图的命令：	with	deleting	the
\begin{lstlisting}
/analysis/h1/create        	# Create 1D histogram
name title [nbin min max] [unit] [fcn] [binScheme]		
\end{lstlisting}	
The commands to create 2D histogram:

创建二维直方图的命令：	
\begin{lstlisting}		
/analysis/h2/create	# Create 2D histogram
name title [nxbin xmin xmax xunit xfcn xbinScheme nybin ymin ymax yunit yfcn yBinScheme]	
\end{lstlisting}
The commands to create 3D histogram:
创建三维直方图的命令：

\begin{lstlisting}
/analysis/h3/create	# Create 3D histogram
name title [nxbin xmin xmax xunit xfcn xbinScheme nybin ymin ymax
yunit yfcn yBinScheme nzbin zmin zmax zunit zfcn zBinScheme]
\end{lstlisting}

Configuring Histograms配置直方图

The properties of already created histograms can be changed with use of one of these two functions sets.	For 1D histograms:

已创建的直方图的属性可以使用这两个函数集中的一个来更改。对于一维直方图：
\begin{lstlisting}
G4bool SetH1(G4int id,
G4int nbins, G4double xmin, G4double xmax,
const G4String& unitName = "none",
const G4String& fcnName = "none",
const G4String& binSchemeName = "linear");
G4bool SetH1(G4int id,
const std::vector<G4double>& edges,
const G4String& unitName = "none",
const G4String& fcnName = "none");
\end{lstlisting}
for 2D histograms:
对于2D直方图：
\begin{lstlisting}
G4bool SetH2(G4int id,
G4int nxbins, G4double xmin, G4double xmax,
 G4int nybins, G4double ymin, G4double ymax,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
 const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& xbinSchemeName = "linear",
const G4String& ybinSchemeName = "linear");
G4bool SetH2(G4int id,
const std::vector<G4double>& xedges,
const std::vector<G4double>& yedges,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none");
\end{lstlisting}
and for 3D histograms:

对于3D直方图：
\begin{lstlisting}
G4bool SetH3(G4int id,
G4int nxbins, G4double xmin, G4double xmax,
G4int nzbins, G4double zmin, G4double zmax,
G4int nybins, G4double ymin, G4double ymax,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& zunitName = "none",
 const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none",
const G4String& xbinSchemeName = "linear",
const G4String& ybinSchemeName = "linear",
const G4String& zbinSchemeName = "linear");
G4bool SetH3(G4int id,
const std::vector<G4double>& xedges,
const std::vector<G4double>& yedges,
 const std::vector<G4double>& zedges,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none");
\end{lstlisting}
The histogram is accessed via its integer identifier. The meaning of the other parameters is the same as in “Create” functions.

直方图通过其整数标识符进行访问。 其他参数的含义与“Create”函数中的含义相同。

Histogram properties can be also defined via UI commands. The commands to define 1D histogram

直方图属性也可以通过UI命令定义。 用于定义一维直方图的命令：
\begin{lstlisting}
/analysis/h1/set id nbin min max [unit] [fcn] [binScheme] # Set parameters
\end{lstlisting}
The commands to define 2D histogram:

用于定义2D直方图的命令：
\begin{lstlisting}
# Set parameters for the 2D histogram of #id
/analysis/h2/set
id nxbin xmin xmax xunit xfcn xbinScheme nybin ymin ymax yunit yfcn yBinScheme
# Set parameters per dimension
/analysis/h2/setX id nbin min max [unit] [fcn] [binScheme] # Set x-parameters
/analysis/h2/setY id nbin min max [unit] [fcn] [binScheme] # Set y-parameters
\end{lstlisting}
The commands to define 3D histogram:
用于定义3D直方图的命令：
\begin{lstlisting}
# Set parameters for the 3D histogram of #id
/analysis/h3/set =
id nxbin xmin xmax xunit xfcn xbinScheme nybin ymin ymax yunit yfcn yBinScheme nzbin zmin zmax  ,
→zunit zfcn zBinScheme
# Set parameters per dimension
/analysis/h3/setX id nbin min max [unit] [fcn] [binScheme] # Set x-parameters
/analysis/h3/setY id nbin min max [unit] [fcn] [binScheme] # Set y-parameters
/analysis/h3/setY id nbin min max [unit] [fcn] [binScheme] # Set z-parameters
\end{lstlisting}
A limited set of parameters for histograms plotting, the histogram and the histogram axis titles, can be also defined via functions

直方图绘图，直方图和直方图坐标轴标题等参数也可以通过函数定义
\begin{lstlisting}
G4bool SetH1Title(G4int id, const G4String& title);
G4bool SetH1XAxisTitle(G4int id, const G4String& title);
G4bool SetH1YAxisTitle(G4int id, const G4String& title);
//
G4bool SetH2Title(G4int id, const G4String& title);
G4bool SetH2XAxisTitle(G4int id, const G4String& title);
G4bool SetH2YAxisTitle(G4int id, const G4String& title);
G4bool SetH2ZAxisTitle(G4int id, const G4String& title);
//
G4bool SetH3Title(G4int id, const G4String& title);
G4bool SetH3XAxisTitle(G4int id, const G4String& title);
G4bool SetH3YAxisTitle(G4int id, const G4String& title);
G4bool SetH3ZAxisTitle(G4int id, const G4String& title);
\end{lstlisting}
The corresponding UI commands

相应的UI命令
\begin{lstlisting}
/analysis/h1/setTitle id title	# Set title for the 1D histogram of #id
/analysis/h1/setXaxis id title	# Set x-axis title for the 1D histogram
/analysis/h1/setYaxis id title	# Set y-axis title for the 1D histogram
\end{lstlisting}
The same set of commands is available for the other histogram types and profiles, under the appropriate directory.

在相应的目录下，其他histogram类型和profiles可以使用相同的一组命令。

Filling Histograms填充直方图

The histogram values can be filled using the functions
直方图值可以使用函数填充
\begin{lstlisting}
G4bool FillH1(G4int id, G4double value,
G4double weight = 1.0);
G4bool FillH2(G4int id, G4double xvalue, G4double yvalue,
G4double weight = 1.0);
G4bool FillH3(G4int id,
G4double xvalue, G4double yvalue, G4double zvalue,
G4double weight = 1.0);
\end{lstlisting}
where the weight can be given optionally.
可以选择赋予权重。

The histograms can be also scaled with a given factor using the functions:
直方图也可以使用函数按给定的因子进行缩放：

\begin{lstlisting}
G4bool ScaleH1(G4int id, G4double factor);
G4bool ScaleH2(G4int id, G4double factor);
G4bool ScaleH3(G4int id, G4double factor);
\end{lstlisting}
Accessing Histograms访问直方图

Besides the fast access to histograms via their integer identifiers, the histograms can be also accessed by their names using the G4AnalysisManager function providing the conversion from a name in a histogram identifier:

除了通过整数标识符快速访问直方图以外，也可以通过名称访问直方图，使用G4AnalysisManager函数将名称转换为直方图标识符：
\begin{lstlisting}
G4int GetH1Id(const G4String& name, G4bool warn = true) const;
G4int GetH2Id(const G4String& name, G4bool warn = true) const;
G4int GetH3Id(const G4String& name, G4bool warn = true) const;
\end{lstlisting}
If a histogram with a given name is not found, a warning is issued unless it is explicitly disabled by the user. This way is however less efficient and it is not recommended for frequently called functions as e.g. Fill().

如果未找到具有给定名称的直方图，则会发出警告，除非用户明确禁用该警告。 然而，这种方式效率较低，不推荐用于频繁调用的函数，例如Fill()。

The analysis manager provides also the direct access to the g4tools histogram objects. The concrete histogram type is hidden behind a selected namespace. In example B4, the g4tools histogram functions mean() and rms() are called:

分析管理器还提供对g4tools直方图对象的直接访问。 具体的直方图类型隐藏在选定的命名空间后面。 在例子B4中，调用g4tools直方图函数mean()和rms()：
\begin{lstlisting}
auto analysisManager = G4AnalysisManager::Instance();
if ( analysisManager->GetH1(1) ) {
G4cout << "\n ----> print histograms statistic \n" << G4endl;
G4cout << " EAbs : mean = " << analysisManager->GetH1(1)->mean()
<< " rms = " << analysisManager->GetH1(1)->rms(),
<< G4endl;
 // ...
}
\end{lstlisting}
Activation of Histograms激活直方图

The activation option allows the user to activate only selected histograms. When this option is activated, only the histograms marked as activated are returned, filled or saved in a file. This feature is intensively used in extended/electromagnetic examples where all histograms are first created inactivated:

激活选项允许用户仅激活选定的直方图。 当这个选项被激活时，只有标记为激活的直方图被返回，填充或保存在一个文件中。 此功能广泛用于extended/electromagnetic examples，其中首次创建时所有直方图不激活：

\begin{lstlisting}
auto analysisManager = G4AnalysisManager::Instance();
analysisManager->SetActivation(true);
// define histogram parameters name, title, nbins, vmin, vmax
G4int id = analysisManager->CreateH1(name, title, nbins, vmin, vmax); analysisManager->SetH1Activation(id, false);
\end{lstlisting}
and then selected histograms are activated in macros, using the analysis “set” command
然后使用分析“set”命令在宏中激活选定的直方图

\begin{lstlisting}
/analysis/h1/set 1 100 0	50 cm	#track length of primary
/analysis/h1/set 2 100 0 300   none	#nb steps of primary
\end{lstlisting}
The activation option is not switched on by default. It has to be activated either via analysisManager SetActivation(true) call as above or via the UI command:

激活选项默认情况下未打开。 它必须通过上面的分析管理器SetActivation（true）调用或通过UI命令来激活：
\begin{lstlisting}
/analysis/setActivation true|false	# Set activation option
\end{lstlisting}
When no parameters need to be changed a histogram can be activated using “setActivation” command:

当不需要更改参数时，可以使用“setActivation”命令激活直方图：
\begin{lstlisting}
/analysis/h1/setActivation id true|false	# Set activation to histogram #id
/analysis/h1/setActivationToAll true|false # Set activation to all 1D histograms.
\end{lstlisting}
Histograms Properties直方图属性

The	following	properties,	additional	to	those	defined	in	g4tools,	can	be	added	to	histograms	via G4AnalysisManager:

除了那些在g4tools定义的属性外，以下属性可通过G4AnalysisManager能够添加至直方图：

•	Unit: if a histogram is defined with a unit, all filled values are automatically converted to this defined unit and the unit is added to the histogram axis title.

•	Function: if a histogram is defined with a function, the function is automatically executed on the filled values and its name is added to the histogram axis title. When a histogram is defined with both unit and function the unit is applied first. The available functions: log, log10, exp.

•	Binning scheme: user can select logarithmic binning scheme besides the linear one (default). The available binning schemes: linear, log.

•	Activation: see previous section.

•	ASCII option: if activated the histogram is also printed in an ASCII file when Write() function is called.

•	Plotting option: if activated the histogram is plotted in a file of Postscript format when Write() function is called. See more details in Plotting.

	单位：如果定义直方图时采用了单位，则所有填充值自动转换为此定义的单位，并将该单位添加到直方图轴标题。

	函数：如果使用函数定义直方图，则会自动对填充的值执行该函数，并将其名称添加到直方图轴标题。 当直方图同时定义单位和函数时，首先应用单位。 可用函数：log，log10，exp。

	Binning scheme：用户可以选择线性方式（默认）以外的对数方式。 可用的Binning scheme：线性，对数。

	激活：请参阅前一节。

	ASCII选项：如果激活，当调用Write()函数时，直方图也会打印在ASCII文件中。

	绘图选项：如果激活，当调用Write()函数时，直方图将绘制在Postscript格式的文件中。 在绘图中看到更多细节in Plotting。

\subsection{9.2.4 Profiles}

Profile histograms (profiles) are used to display the mean value of Y and its error for each bin in X. The displayed error is by default the standard error on the mean (i.e. the standard deviation divided by the sqrt(n).) An example of use of 1D profiles can be found in extended/electromagnetic/TestEm2. Though the functions for creating and manipulating profiles are very similar to those for histograms, they are described in this section.

Profile histograms (profiles)用于显示X的平均值Y及其每个bin的误差。显示的误差默认为平均值的标准误差（即标准偏差除以sqrt（n）。）在extended/electromagnetic/TestEm2中可以找到使用1D profiles示例。 尽管用于创建和操作Profiles的函数与直方图的功能非常相似，仍在本节中对它们进行了描述。

Creating Profiles

A one-dimensional (1D) profile can be created with one of these two G4AnalysisManager functions
使用这两个G4AnalysisManager函数中的一个可以创建一维（1D）profile
\begin{lstlisting}
G4int CreateP1(const G4String& name, const G4String& title,
G4int nbins, G4double xmin, G4double xmax,
G4double ymin = 0, G4double ymax = 0,
const G4String& xunitName = "none", c
onst G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
 const G4String& xbinSchemeName = "linear");
G4int CreateP1(const G4String& name, const G4String& title,
const std::vector<G4double>& edges,
G4double ymin = 0, G4double ymax = 0,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none");
\end{lstlisting}
where name and title parameters are self-descriptive. The profile edges can be defined either via the nbins, xmin and xmax parameters (first function) representing the number of bins, the minimum and maximum profile values, or via the const std::vector<G4double>\& edges parameter (second function) representing the edges defined explicitly. If ymin and ymax parameters are provides, only values between these limits will be considered at filling time. The other parameters in both functions are optional and their meaning is explained in Profiles Properties.

其中名称和标题参数是自描述性的。 Profile范围可以通过nbins，xmin和xmax参数（第一个函数）定义，分别代表bins的数量，最小值和最大值，或者通过const std :: vector <G4double>＆edges参数（第二个函数）代表显式定义的范围。 如果提供ymin和ymax参数，则只有在这些限制之间的值才会在填充时考虑。 两个函数中的其他参数都是可选的，其含义在“Profiles Properties”中进行了说明。

A two-dimensional (2D) profile can be created with one of these two functions analogous to those for 1D profiles:

可以使用与1D profiles类似的这两种功能之一来创建二维（2D）profiles：

\begin{lstlisting}
G4int CreateP2(const G4String& name, const G4String& title,
G4int nxbins, G4double xmin, G4double xmax,
G4int nybins, G4double ymin, G4double ymax,
G4double zmin = 0, G4double zmax = 0,
const G4String& xunitName = "none",		
const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none",
const G4String& xbinSchemeName = "linear",
const G4String& ybinSchemeName = "linear");
G4int CreateP2(const G4String& name, const G4String& title,
 const std::vector<G4double>& xedges,
const std::vector<G4double>& yedges,
G4double zmin = 0, G4double zmax = 0,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none");		
\end{lstlisting}
The meaning of parameters is the same as in the functions for 1D profiles, they are just applied in x, y and z dimensions.

参数的含义与1D profiles的功能相同，它们仅应用于x，y和z维度。

The profiles created with G4AnalysisManager get automatically attributed an integer identifier which value is returned from the “Create” function. The default start value is 0 and it is incremented by 1 for each next created profile. The numbering of 2D profiles is independent from 1D profiles and so the first created 2D profile identifier is equal to the start value even when several 1D profiles have been already created.

使用G4AnalysisManager创建的profiles会自动归属一个整数标识符，该标识符是从“创建”函数返回的值。 默认的起始值为0，并且对于每下一个创建的profiles，它都会加1。  2D profiles的编号与1D profiles无关，所以即使已经创建了几个1D profiles，第一个创建的2D profiles标识也等于起始值，仍然开始于0。

The start profile identifier value can be changed either with the SetFirstProfileId(G4int) method, which applies the new value to both 1D and 2D profile types, or with the SetFirstPNId(G4int), where N = 1, 2 methods, which apply the new value only to the relevant profile type.

profiles的整数标识符可以被修改，可以使用SetFirstProfileId（G4int）方法将新的值应用于所有直方图类型的或使用SetFirstPNId（G4int）（其中N = 1,2）方法来改变起始profiles标识符值，其中应用新值只有相关的(N的三个值对应于1维、2维) profiles类型。

All profiles created by G4AnalysisManager are automatically deleted with deleting the G4AnalysisManager object.

Profiles can be also created via UI commands. The commands to create 1D profile
所有由G4AnalysisManager创建的profiles都会自动删除，并删除G4AnalysisManager对象。profiles也可以通过UI命令创建。 用于创建1D profiles的命令。

\begin{lstlisting}
/analysis/p1/create	# Create 1D profile
name title [nxbin xmin xmax xunit xfcn xbinScheme ymin ymax yunit yfcn]
\end{lstlisting}

The commands to create 2D profile:

创建2D profiles的命令：

\begin{lstlisting}
/analysis/p2/create	# Create 2D profile
name title [nxbin xmin xmax xunit xfcn xbinScheme nybin ymin ymax yunit yfcn yBinScheme zmin
,→zmax zunit zfcn]
\end{lstlisting}

Configuring Profiles

The properties of already created profiles can be changed with use of one of these two functions sets. For 1D profiles

已经创建的profiles的属性可以使用这两个函数集中的一个来更改。 对于1D profiles和2D profiles：
\begin{lstlisting}
G4bool SetP1(G4int id,
G4int nbins, G4double xmin, G4double xmax,
G4double ymin = 0, G4double ymax = 0,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& xbinSchemeName = "linear");
G4bool SetP1(G4int id,
const std::vector<G4double>& edges,
G4double ymin = 0, G4double ymax = 0,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none");
and for 2D profiles:

G4bool SetP2(G4int id,
G4int nxbins, G4double xmin, G4double xmax,
G4int nybins, G4double ymin, G4double ymax,
G4double zmin = 0, G4double zmax = 0,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none",
const G4String& xbinSchemeName = "linear",
const G4String& ybinSchemeName = "linear");
G4bool SetP2(G4int id,
const std::vector<G4double>& xedges,
const std::vector<G4double>& yedges,
G4double zmin = 0, G4double zmax = 0,
const G4String& xunitName = "none",
const G4String& yunitName = "none",
const G4String& zunitName = "none",
const G4String& xfcnName = "none",
const G4String& yfcnName = "none",
const G4String& zfcnName = "none");
\end{lstlisting}
The profile is accessed via its integer identifier. The meaning of the other parameters is the same as in “Create” functions.

该profiles通过其整数标识符进行访问。 其他参数的含义与“创建”功能中的含义相同。

Profiles properties can be also defined via UI commands. The commands to define 1D profile
profiles属性也可以通过UI命令进行定义。 用于定义1D profiles的命令
\begin{lstlisting}
/analysis/p1/set	# Set parameters for the 1D histogram of #id
id nxbin xmin xmax xunit xfcn xbinScheme ymin ymax yunit yfcn
\end{lstlisting}
The commands to create or define 2D profile:
用于创建或定义2D profiles的命令：
\begin{lstlisting}
/analysis/p2/set	# Set parameters for the 2D profile of #id
id nxbin xmin xmax xunit xfcn xbinScheme nybin ymin ymax yunit yfcn yBinScheme zmin zmax zunit
,→zfcn
\end{lstlisting}
A limited set of parameters for profiles plotting, the profile and the profile axis titles, can be also defined via functions

可以通过函数定义profiles绘图，profiles和profiles轴标题的一组有限参数
\begin{lstlisting}
G4bool SetP1Title(G4int id, const G4String& title);
G4bool SetP1XAxisTitle(G4int id, const G4String& title);
G4bool SetP1YAxisTitle(G4int id, const G4String& title);
//
G4bool SetP2Title(G4int id, const G4String& title);
G4bool SetP2XAxisTitle(G4int id, const G4String& title);
G4bool SetP2YAxisTitle(G4int id, const G4String& title);
G4bool SetP2ZAxisTitle(G4int id, const G4String& title);
\end{lstlisting}
The parameters can be also set via the same set of UI commands as the histogram parameters available under the appro priate directory.

参数也可以通过相应目录下可用的直方图参数相同的一组UI命令来设置。

Filling Profiles

The profile values can be filled using the functions:
profile的值可以使用以下函数填充：
\begin{lstlisting}
G4bool FillP1(G4int id,
G4double xvalue, G4double yvalue,
G4double weight = 1.0);
G4bool FillP2(G4int id,
G4double xvalue, G4double yvalue, G4double zvalue,
G4double weight = 1.0);
\end{lstlisting}
where the weight can be given optionally.
可以选择赋予权重。

The profiles can be also scaled with a given factor using the functions:
profile还可以使用以下函数按给定因子进行缩放：
\begin{lstlisting}
G4bool ScaleP1(G4int id, G4double factor);
G4bool ScaleP2(G4int id, G4double factor);
\end{lstlisting}
Profiles Properties

All histogram features described in sections “Accessing Histograms”, “Activation of Histograms” and “Histograms Properties” (Accessing Histograms, Activation of Histograms and Histograms Properties) are also available for profiles.

在“访问直方图”，“直方图激活”和“直方图属性”（访问直方图，直方图激活和直方图属性）部分中描述的所有直方图特征也可用于profile。
\subsection{9.2.5 Plotting【画图】}
Since GEANT4 10.2 version it is possible to produce a graphics output file in the Postscript format containing selected histograms and profiles. Histograms and profiles plotting can be activated using G4AnalysisManager functions:

自从GEANT4 10.2版本可以生成包含选定直方图和profiles的Postscript格式的图形输出文件。 使用G4AnalysisManager函数可以激活Histograms and profiles plotting：
\begin{lstlisting}
auto analysisManager = G4AnalysisManager:: Instance();
analysisManager->SetH1Plotting(id, true);
// etc for H2, H3, P1, P2	
\end{lstlisting}
or using the UI commands
或使用UI命令	
\begin{lstlisting}
/analysis/h1/setPlotting id true|false	# (In)Activate plottig for 1D histogram #id
/analysis/h1/setPlottingToAll true|false
# etc. for h2, h3, p1, p2	# (In)Activate plotting for all 1D histograms.
\end{lstlisting}
If GEANT4 libraries are built with support for Freetype font rendering, user can choose from three plotting styles:

•	ROOT\_default: ROOT style with high resolution fonts (default)

•	hippodraw: hippodraw style with high resolution fonts • inlib\_default: PAW style with low resolution fonts”) otherwise only the inlib\_default style with low resolution fonts is available.
如果GEANT4库支持Freetype字体渲染，则用户可以从三种绘图风格中进行选择：

	ROOT\_default：具有高分辨率字体的ROOT样式（默认）

	hippodraw：具有高分辨率字体的hippodraw样式

	inlib\_default：具有低分辨率字体的PAW样式

否则只有具有低分辨率字体的inlib\_default样式可用。

The page size of the graphics output is fixed to A4 format. Users can choose the page layout which is defined by the number columns and the number of rows in a page. Depending on the selected plotting style, the maximum number of plots is limited to 3 columns x 5 rows for the styles with high resolution fonts and to 2 columns x 3 rows for the inlib\_default style.

图形输出的页面大小固定为A4格式。 用户可以选择列和行来设计页面布局。 根据选定的绘图样式，对于高分辨率字体样式，绘图的最大数量限制为3列x 5行，对于inlib\_default样式，绘图的最大数量限制为2列× 3行。

Finally, users can also customize the plot dimensions, which represent the plotter window size (width and height) in pixels.

最后，用户还可以自定义绘图窗口尺寸（宽度和高度）的绘图尺寸（以像素为单位）。

The customization of the plotting can be done via the UI commands in /analysis/plot directory:

绘图的自定义可以通过/ analysis / plot目录中的UI命令完成：
\begin{lstlisting}
/analysis/plot/setStyle styleName
/analysis/plot/setLayout columns rows
/analysis/plot/setDimensions width height
\end{lstlisting}
Opening more configuration parameters for users customisation can be considered in future according to the users feedback.

根据用户反馈，今后可以考虑为用户定制打开更多配置参数。
\subsection{9.2.6 Ntuples}

In the following example the code for handling ntuples extracted from basic example B4, from the B4RunAction and B4EventAction classes, is presented.

在下面介绍了从basic example B4的B4RunAction和B4EventAction类中提取的ntuples的代码。
\begin{lstlisting}
#include "B4Analysis.hh"
B4RunAction::B4RunAction()
: G4UserRunAction()
{
// Create analysis manager // ...
// Create ntuple
man->CreateNtuple("B4", "Edep and TrackL"); man->CreateNtupleDColumn("Eabs"); man->CreateNtupleDColumn("Egap");
man->FinishNtuple();
}
void B4EventAction::EndOfEventAction(const G4Run* aRun)
{
G4AnalysisManager* man = G4AnalysisManager::Instance(); man->FillNtupleDColumn(0, fEnergyAbs);
man->FillNtupleDColumn(1, fEnergyGap);
man->AddNtupleRow();
}
\end{lstlisting}
Since 10.0 release, there is no limitation for the number of ntuples that can be handled by G4AnalysisManager. Handling of two ntuples is demonstrated in extended analysis/AnaEx01 example.
自10.0版本发布以来，G4AnalysisManager可以处理的ntuples数量没有限制。 在extended analysis/AnaEx01 example中演示了处理两个ntuples。

Creating Ntuples

An ntuple can be created using the following set of functions:
可以使用以下一组函数创建一个ntuple：
\begin{lstlisting}
G4int CreateNtuple(const G4String& name, const G4String& title);
// Create columns in the last created ntuple
G4int CreateNtupleXColumn(const G4String& name);
void FinishNtuple();
// Create columns in the ntuple with given id
G4int CreateNtupleXColumn(G4int ntupleId, const G4String& name);
void FinishNtuple(G4int ntupleId);
\end{lstlisting}
The first set is demonstrated in the example. The columns can take the values of G4int, G4float, G4double or G4String type which is also reflected in the CreateNtupleXColumn() function names. where X can be I,

F, D or S.

示例中演示了第一组。 这些列可以使用G4int，G4float，G4double或G4String类型的值，这些值也反映在CreateNtupleXColumn（）函数名称中。  X可以是I，F，D或S.

It is also possible to define ntuple columns of std::vector of G4int, G4float or G4double values using the functions:

也可以使用以下函数定义G4int，G4float或G4double值的std :: vector的int列：
\begin{lstlisting}
// Create columns of vector in the last created ntuple
G4int CreateNtupleXColumn(
const G4String& name, std::vector<Xtype>& vector);
// Create columns of vector in the ntuple with given id
G4int CreateNtupleXColumn(G4int ntupleId,
const G4String& name, std::vector<Xtype>& vector);	
\end{lstlisting}
where [X, Xtype] can be [I, G4int], [F, G4float] or [D, G4double].
其中[X，Xtype]可以是[I，G4int]，[F，G4float]或[D，G4double]。

When all ntuple columns are created, the ntuple has to be closed using FinishNtuple() function.
The ntuples created with G4AnalysisManager get automatically attributed an integer identifier which value is returned from the “Create” function. The default start value is 0 and it is incremented by 1 for each next created ntuple. The start ntuple identifier value can be changed with the SetFirstNtupleId(G4int) function.

当创建所有的ntuple 列时，必须使用FinishNtuple（）函数关闭该ntuple。

使用G4AnalysisManager创建的ntuples会自动归属一个整数标识符，该标识符的值是从“Create”函数返回的。 默认的起始值是0，并且对于每个下一个创建的ntuple，它会增加1。 可以使用SetFirstNtupleId（G4int）函数更改开始ntuple标识符值。

The integer identifiers are also attributed to the ntuple columns. The numbering of ntuple columns is independent for each ntuple, the identifier default start value is 0 and it is incremented by 1 for each next created column regardless its type (I, F, D or S). (If the third ntuple column of a different type than double (int or float) is created in the demonstrated example, its identifier will have the value equal 2.) The start ntuple column identifier value can be changed with the SetFirstNtupleColumnId(G4int) function.

整数标识符也属于ntuple列。 无论其类型（I，F，D还是S），每个下标的默认开始值都是0，并且对于每下一个创建的列，它的值会加1。  （如果在演示示例中创建了不同的double类型（int或float）的第三个ntuple列，则其标识符的值将等于2。）可以使用SetFirstNtupleColumnId（G4int）函数更改start ntuple列标识符值。

When calls to CreateNtuple-Column() and FinishNtuple() succeed the call to CreateNtuple(), the ntupleId argument need not to be specified even when creating several ntuples. However this order is not enforced and the second set of functions with ntupleId argument is provided to allow the user to create the ntuples and their columns in whatever order.

当对CreateNtuple-Column()和FinishNtuple()的调用成功完成对CreateNtuple()的调用时，即使创建多个ntuples，也不需要指定ntupleId参数。 然而，这个顺序并没有被强制执行，并且提供了带有ntupleId参数的第二组函数，以允许用户以任何顺序创建链接和它们的列。

All ntuples and ntuple columns created by G4AnalysisManager are automatically deleted with deleting the G4AnalysisManager object.

通过删除G4AnalysisManager对象，将自动删除由G4AnalysisManager创建的所有ntuples和ntuple列。

Filling Ntuples

The ntuple values can be filled using the functions:
可以使用以下函数来填充ntuple值：

\begin{lstlisting}
// Methods for ntuple with id = FirstNtupleId
G4bool FillNtupleIColumn(G4int id, G4int value);
G4bool FillNtupleFColumn(G4int id, G4float value);
G4bool FillNtupleDColumn(G4int id, G4double value);
G4bool FillNtupleSColumn(G4int id, const G4String& value);
G4bool AddNtupleRow();
// Methods for ntuple with id > FirstNtupleId (when more ntuples exist)
G4bool FillNtupleIColumn(G4int ntupleId, G4int columnId, G4int value);
G4bool FillNtupleFColumn(G4int ntupleId, G4int columnId, G4float value);
G4bool FillNtupleDColumn(G4int ntupleId, G4int columnId, G4double value);
G4bool FillNtupleSColumn(G4int ntupleId, G4int id, const G4String& value);
G4bool AddNtupleRow(G4int ntupleId);
\end{lstlisting}
If only one ntuple is defined in the user application, the ntuple identifier, ntupleId, need not to be specified and the first set can be used. The second set of functions has to be used otherwise. When all ntuple columns are filled, the ntuple fill has to be closed by calling AddNtupleRow().

如果在用户应用程序中只定义了一个ntuple，则不需要指定ntuple标识符ntupleId，并且可以使用第一个套将被使用。第二套函数必须另外使用。当所有的双列填充完成后，必须通过调用AddNtupleRow（）来关闭整个填充。

Accessing Ntuples
The ntuples g4tools objects can be accessed by their identifier. The concrete ntuple type is hidden behind a selected namespace:
ntuples g4tools对象可以通过它们的标识符来访问。 具体的ntuple类型隐藏在选定的命名空间后面：
\begin{lstlisting}
auto analysisManager = G4AnalysisManager::Instance();
// If only one ntuple is defined
G4Ntuple* ntuple = analysisManager->GetNtuple();
// If more ntuples
G4int ntuple id = ...;
G4Ntuple* ntuple = analysisManager->GetNtuple(ntupleId);
\end{lstlisting}
\subsection{9.2.7 Parallel Processing}

As well as all other GEANT4 categories, the analysis code has been adapted for multi-threading. In multi-threading mode, the analysis manager instances are internally created on the master and thread workers and data accounting is processed in parallel on workers threads.

与所有其他GEANT4类一样，分析代码也适用于多线程。 在多线程模式下，分析管理器实例在主线程和工作线程内部创建，并且数据计算在工作线程上并行处理。

Histograms produced on thread workers are automatically merged on Write() call and the result is written in a master file. Merging is protected by a mutex locking, using G4AutoLock utility.

工作线程生成的直方图会在Write()调用中自动合并，并将结果写入主文件中。 使用G4AutoLock utility来对合并进行互斥锁（mutex locking）保护。

Ntuples produced on thread workers are, by default, written on separate files, which names are generated automatically from a base file name, a thread identifier and eventually also an ntuple name. Since GEANT4 version 10.3 it is possible to activate merging of ntuples with ROOT output type:

在工作线程上生成的Ntuples，默认情况下写在单独的文件上，这些文件的名称是从一个基本文件名，一个线程标识符以及最终的一个单元名自动生成的。 从GEANT4版本10.3开始，可以激活具有ROOT输出类型的ntuples合并：
\begin{lstlisting}
auto analysisManager = G4AnalysisManager::Instance();
analysisManager->SetNtupleMerging(true);
\end{lstlisting}
The ntuples produced on workers will be then progressively being merged to the main ntuples on the master. By default, the ntuples are written at the same file as the final histograms. Users can also select merging in a given number of files or change the default basket size value (32000):

工作线程产生的ntuples会逐渐合并到主线程。 默认情况下，这些ntuples与最终直方图一样写入相同的文件。 用户还可以选择在给定数量的文件中合并或更改默认尺寸值（32000）：
\begin{lstlisting}
auto analysisManager = G4AnalysisManager::Instance();
G4int nofReducedNtupleFiles = 2;
G4int basketSize = 64000;
analysisManager->SetNtupleMerging(true, nofReducedNtupleFiles, basketSize);
\end{lstlisting}
No merging of ntuples is provided with HDF5, CSV and AIDA XML formats.

No changes are required in the user client analysis code for migration to multi-threading. It is however recommended to instantiate and delete the analysis manager in the user run action constructor and destructor respectively. The master instance is necessary when histograms are used in the user application or if merging ntuples is selected (available only with ROOT output); in case only ntuples are in use and merging is not activated, the master instance need not to be created.

To simplify the scaling of a GEANT4 application across nodes on a cluster GEANT4 provides the support of MPI. In particular it is possible to run a hybrid MPI/MT application that uses MPI to scale across nodes and MT to scale across cores. This is demonstrated in the extended example parallel/MPI/exMPI03 which includes usage of GEANT4 analysis.

HDF5，CSV和AIDA XML格式不提供合并ntuples。

在用户客户端分析代码中不需要对迁移到多线程进行更改。 但是，建议用户分别在run 的构造函数和析构函数中实例化和删除分析管理器。 在用户应用程序中使用直方图或选择合并ntuples时，主实例是必需的（仅适用于ROOT输出）; 如果使用ntuples并且合并未被激活，则不需要创建主实例。

为了简化GEANT4应用程序跨集群节点的扩展，GEANT4提供了对MPI的支持。 特别是可以运行混合MPI / MT应用程序，该应用程序使用MPI跨节点进行扩展，MT可跨内核进行扩展。 这在extended example parallel/MPI/exMPI03中得到了证明。

\subsection{9.2.8 Coexistence of Several Managers}

The specific manager classes are singletons and so it is not possible to create more than one instance of an analysis manager of one type, e.g. G4RootAnalysisManager. However two analysis manager objects of different types can coexist. Then instead of the generic G4AnalysisManager typedef the concrete type of each manager has to be given explicitly.

特定的管理器类是singletons，因此不可能创建同一一个类型的分析管理器的多个实例，例如G4RootAnalysisManager。 但是，不同类型的两个分析管理器对象可以共存。 然后，而不是利用通用的G4AnalysisManager typedef给出，每个管理器的具体类型必须明确给出。
\begin{lstlisting}
#include "G4CsvAnalysisManager.hh"
#include "G4XmlAnalysisManager.hh"
G4CsvAnalysisManager* csvManager = G4CsvAnalysisManager::Instance();
G4XmlAnalysisManager* xmlManager = G4XmlAnalysisManager::Instance();
Or:
#include "g4csv_defs.hh"
#include "g4xml_defs.hh"
G4Csv::G4AnalysisManager* csvManager = G4Csv::G4AnalysisManager::Instance();
G4Xml::G4AnalysisManager* xmlManager = G4Xml::G4AnalysisManager::Instance();
\end{lstlisting}
\subsection{9.2.9 Supported Features and Limitations}
The analysis category based on g4tools is provided with certain limitations that can be reduced according to the feedback from GEANT4 users and developers.

Below is a summary of currently supported features in Root, Hdf5, Csv and Xml manager classes:
根据GEANT4用户和开发人员的反馈，可以减少基于g4tools的分析类别的某些限制。
以下是Root，Hdf5，Csv和Xml管理器类中当前支持的功能的总结：

•	Histogram types: 1D, 2D, 3D of double

•	Profile types: 1D, 2D of double

•	Ntuple column types: int, float, double, G4String, std::vector<int>, std::vector<float>,std::vector<double>

•	Optional directory structure limited to one directory for histograms and/or one for ntuples

\section{9.3 Analysis Reader Classes}
The analysis reader classes allow to read in g4analysis objects from the files generated by the analysis manager(s) during processing GEANT4 application.

An analysis reader class is available for each supported output format:

分析读取器类允许在处理GEANT4应用程序期间从分析管理器生成的文件中读取g4分析对象。

分析阅读器类适用于每种支持的输出格式｛translate by 小二｝：

•	G4CsvAnalysisReader

•	G4Hdf5AnalysisReader

•	G4RootAnalysisReader

•	G4XmlAnalysisReader

For a simplicity of use, each analysis manager provides the complete access to all interfaced functions though it is implemented via a more complex design.

The readers are implemented as singletons. User code will access a pointer to a single instance of the desired reader object. The reader has to be created and deleted from the user code. All objects created via analysis reader are deleted automatically with the manager. The concrete types of the analysis reader as well as the handled g4tools objects, are hidden behind a namespace which is selected by including a dedicated include file. This allows the user to use all output technologies in an identical way via these generic types:

为了简化使用，每个分析管理器都提供了对所有接口函数的完整访问，尽管它是通过更复杂的设计实现的。

读者被实现为singletons。 用户代码将访问指向所需阅读器对象的单个实例的指针。 必须从用户代码创建和删除阅读器。 通过分析阅读器创建的所有对象都会与管理器自动删除。 分析阅读器的具体类型以及处理的g4tools对象隐藏在通过包含专用包含文件选择的名称空间后面。 这允许用户通过这些泛型类型以相同的方式使用所有输出技术：


•	G4AnalysisReader: the public reader interface

•	G4AnaH1[2,3]: one[two,three]-dimensional histogram

•	G4AnaP1[2]: one[two]-dimensional profile

•	G4RNtuple: read ntuple

While the histograms and profiles objects handled by the analysis reader are of the same type as those handled by the analysis manager, the reader’s ntuple type is different.

All objects read with G4AnalysisReader (histograms, profiles and ntuples) get automatically attributed an integer identifier which value is returned from the “Read” or “GetNtuple” function. The default start value is 0 and it is incremented by 1 for each next created object. The numbering each object type is independent from other objects types and also from the numbering of the same object type in analysis manager. The start identifier value can be changed in the same way as with the analysis manager (see Creating Histograms).

The read objects can be accessed in the analysis reader via their integer identifiers or by their names in the same way as in the analysis manager (see Accessing Histograms). Note that the type of read ntuple is different from the ntuple type in the analysis manager.

The specific manager classes are singletons and so it is not possible to create more than one instance of an analysis reader of one type, e.g. G4RootAnalysisReader. However two analysis reader objects of different types can coexist. Then instead of the generic G4AnalysisReader typedef the concrete type of each manager has to be given explicitly in a similar way as for the analysis managers (see Coexistence of Several Managers).

As well as all other GEANT4 categories, the analysis code has been adapted for multi-threading. In multi-threading mode, the analysis reader instances are internally created on the master or thread workers, depending on the client code call, and data reading can be processed in parallel on workers threads.

虽然分析阅读器处理的直方图和profiles对象与分析管理器处理的直方图和profiles对象属于同一类型，但阅读器处理ntuple类型不同。

使用G4AnalysisReader（直方图，profiles和ntuples）读取的所有对象都会自动归属一个整数标识符，该标识符从“读取”或“GetNtuple”函数返回。 默认的起始值是0，并为每个下一个创建的对象增加1。 每个对象类型的编号都是独立于其他对象类型的，也是分析管理器中相同对象类型的编号。 起始标识符值可以按照与分析管理器相同的方式进行更改（请参阅创建直方图）。

读取的对象可以通过分析读取器中的整数标识符或其名称以与分析管理器中相同的方式访问（请参阅访问直方图）。 请注意，读取ntuple的类型与分析管理器中的ntuple类型不同。

特定的管理器类是singletons，因此不可能创建一个类型的分析阅读器的多个实例，例如G4RootAnalysisReader。 然而，两种不同类型的分析阅读器对象可以共存。 然后，而不是通用的G4AnalysisReader类型创建，每个管理器的具体类型必须以与分析管理器类似的方式明确给出（请参阅多个管理器的共存）。

与所有其他GEANT4类别一样，分析代码也适用于多线程。 在多线程模式下，根据客户端代码调用，分析阅读器实例在主线程或工作线程内部创建，并且可以在工作线程上并行处理数据读取。

\subsection{9.3.1 Analysis Reader}

For reading in the output files created with G4AnalysisManager, an instance of the analysis reader must be created. The analysis reader object is created with the first call to G4AnalysisReader::Instance(), the next calls to this function will just provide the pointer to this analysis manager object. The client code is responsible for deleting the created object.

The example of the code for creating the analysis reader is given below:

为了读取使用G4AnalysisManager创建的输出文件，必须创建分析阅读器的实例。 分析阅读器对象是在第一次调用G4AnalysisReader :: Instance（）时创建的，接下来对这个函数的调用只会提供指向这个分析管理器对象的指针。 客户端代码负责删除创建的对象。
创建分析阅读器的代码示例如下：
\begin{lstlisting}
#include "g4root.hh"
//#include "g4csv.hh"
//#include "g4xml.hh"
//#include "g4hdf5.hh"
// Create (or get) analysis reader
G4AnalysisReader* analysisReader = G4AnalysisReader::Instance();
analysisReader->SetVerboseLevel(1);
// code to read data
// Delete analysis reader
delete G4AnalysisReader::Instance();
\end{lstlisting}
The level of informative printings can be set by SetVerboseLevel(G4int). Currently the levels from 0 (default) up to 4 are supported.

信息打印的级别可以通过SetVerboseLevel（G4int）来设置。 目前支持从0（默认）到4的级别。
\subsection{9.3.2 File handling}
The name of file to be read can be specified either via G4AnalysisReader::SetFileName() function, or directly when reading an object. It is possible to change the base file name at any time. The analysis reader can handle more than one file at same time.

要读取的文件的名称可以通过G4AnalysisReader :: SetFileName()函数指定，也可以直接在读取对象时指定。 可以随时更改基本文件名称。 分析阅读器可以同时处理多个文件。

\begin{lstlisting}
G4AnalysisReader* analysisReader = G4AnalysisReader::Instance();
// Define a base file name
analysisReader->SetFileName("MyFileName");
\end{lstlisting}
The following functions are defined for handling files:
为处理文件定义了以下功能：
\begin{lstlisting}
void SetFileName(const G4String& fileName);
G4String GetFileName() const;
\end{lstlisting}
A file is open only when any “Read” function is called. When more objects are read from the same file (Xml, Root), the file is open only once. When reading an object without specifying the file name explicitly in “Read” call, the object is searched in all open files in the order of their creation time.

只有在调用任何“读取”函数时才打开文件。 当从同一文件（Xml，Root）读取更多对象时，该文件仅打开一次。 当在“Read”调用中没有明确指定文件名称的情况下读取对象时，将按照创建时间的顺序在所有打开的文件中搜索对象。
\subsection{9.3.3 Histograms and Profiles}
In the following example the code for reading an histogram is presented.

在下面的例子中，介绍了读取直方图的代码。
\begin{lstlisting}
// Code to create (or get) analysis reader
G4AnalysisReader* analysisReader = G4AnalysisReader::Instance();
// Define a base file name
analysisReader->SetFileName("MyFileName");
// Read 1D histogram of "Edep" name
G4int h1Id = analysisReader->ReadH1("Edep");
if ( h1Id >= 0 ) {
G4H1* h1 = analysisReader->GetH1(h1Id);
9.3. Analysis Reader Classes
if ( h1 ) {
	G4cout << "	H1: "
	<< "	mean: " << h1->mean() << " rms: " << h1->rms() << G4endl;
}
}
// Delete analysis reader delete G4AnalysisReader::Instance();
\end{lstlisting}
The histograms and profiles can be read with these G4AnalysisReader functions:
这些G4AnalysisReader函数可以读取直方图和配置文件：
\begin{lstlisting}
G4int ReadH1(const G4String& h1Name, const G4String& fileName = "");
G4int ReadH2(const G4String& h2Name, const G4String& fileName = "");
G4int ReadH3(const G4String& h3Name, const G4String& fileName = "");
G4int ReadP1(const G4String& h1Name, const G4String& fileName = "");
G4int ReadP2(const G4String& h2Name, const G4String& fileName = "");
\end{lstlisting}
where hNname is the name of the object to be read from a file. The file name can be defined explicitly for each reading object.

All histograms and profiles created by G4AnalysisReader are automatically deleted with deleting the G4AnalysisReader object.

其中hNname是要从文件中读取的对象的名称。 文件名可以为每个读取对象显式定义。
由G4AnalysisReader创建的所有直方图和profiles将自动删除，同时删除G4AnalysisReader对象。
\subsection{9.3.4 Ntuples}
In the following example the code for reading ntuples is presented.
在下面的例子中，给出了读取ntuples的代码。
\begin{lstlisting}
// Code to create (or get) analysis reader
G4AnalysisReader* analysisReader = G4AnalysisReader::Instance();
// Define a base file name
analysisReader->SetFileName("MyFileName");
// Read ntuple
G4int ntupleId = analysisReader->GetNtuple("TrackL");;
if ( ntupleId >= 0 ) {
G4double trackL;
analysisReader->SetNtupleDColumn("Labs", trackL);
G4cout << "Ntuple TrackL, reading selected column Labs" << G4endl;
while ( analysisReader->GetNtupleRow() ) {
G4cout << counter++ << "th entry: "
<< " TrackL: " << trackL << std::endl;
}
}
// Delete analysis reader delete G4AnalysisReader::Instance();
\end{lstlisting}
When the ntuple columns are associated with the variables of the appropriate type, the ntuple they can be read in a loop with GetNtupleRow() function. The function returns true until all data are read in.
An overview of all available functions for ntuple reading is given below:

当ntuple列与适当类型的变量相关联时，可以使用GetNtupleRow（）函数在循环中读取它们。 该函数返回true，直到读入所有数据。
以下给出了所有可用于完整阅读的功能的概述：
\begin{lstlisting}
// Methods to read ntuple from a file
G4int GetNtuple(const G4String& ntupleName, const G4String& fileName = "");
// Methods for ntuple with id = FirstNtupleId
G4bool SetNtupleXColumn(const G4String& columnName, Xtype& value);
G4bool SetNtupleXColumn(const G4String& columnName, std::vector<Xtype>& vector);
G4bool GetNtupleRow();
// Methods for ntuple with id > FirstNtupleId
G4bool SetNtupleXColumn(G4int ntupleId,
const G4String& columnName, Xtype& value);
G4bool SetNtupleXColumn(G4int ntupleId,
const G4String& columnName, std::vector<Xtype>& vector);
G4bool GetNtupleRow(G4int ntupleId);
\end{lstlisting}
where [X, Xtype] in SetNtupleXColumn() can be [I, G4int], [F, G4float], [D, G4double] or [S, G4String]. The columns of std::vector type are not supported for G4String.

All ntuples and ntuple columns created by G4AnalysisReader are automatically deleted with deleting the G4AnalysisReader object.

SetNtupleXColumn()中的[X，Xtype]可以是[I，G4int]，[F，G4float]，[D，G4double]或[S，G4String]。  G4String不支持std :: vector类型的列。

所有由G4AnalysisReader创建的ntuples和ntuple列都会自动删除，并删除G4AnalysisReader对象。
\section{9.4 Accumulables}
The classes for users accumulables management were added in 10.2 release for the purpose of simplification of users application code. The accumulables objects are named variables registered to the accumulable manager, which provides the access to them by name and performs their merging in multi-threading mode according to their defined merge mode. Their usage is demonstrated in the basic examples B1 and B3a.

To better reflect the meaning of these objects, the classes base name “Parameter” used in 10.2 was changed in “Accumulable” in 10.3. Further integration in the GEANT4 framework is foreseen in the next GEANT4 versions.

为了简化用户应用程序代码，在10.2版本中添加了用户累积管理类。 可累积对象是已注册到可累积管理器的已命名变量，它提供对它们的名称访问权限，并根据其定义的合并模式在多线程模式下执行合并。 它们的用法在basic examples B1和B3a中得到证明。

为了更好地反映这些对象的含义，10.2中使用的类基本名称“Parameter”在10.3中的“Accumulable”中进行了更改。  GEANT4框架中的进一步集成预计将在下一代GEANT4版本中进行。
\subsection{9.4.1 G4Accumulable<T>}

G4Accumulable<T> templated class can be used instead of built-in types in order to facilitate merging of the values accumulated on workers to the master thread. The G4Accumulable<T> object has, besides its value of the templated type T, also a name, the initial value, which the value is set to in Reset() function and a merge mode, specifying the operation which is performed in Merge() function.

The accumulable object can be either instantiated using its constructor and registered in G4AccumulablesManager explicitly, or it can be created using 
G4AccumulablesManager::CreateAccumulable() function, their registering is then automatic. The first way is used in the basic examples B1 and B3a:

G4Accumulable <T>模板类可以用来代替内置类型，以便于将积累在工作线程的值合并到主线程中。  G4Accumulable <T>对象除了其模板类型T的值外，还具有一个名称，该值在Reset()函数和合并模式中设置为的初始值，指定在Merge()功能。

可累积对象可以使用它的构造函数实例化并明确注册到G4AccumulablesManager中，也可以使用它创建
G4AccumulablesManager :: CreateAccumulable()函数，它们的注册是自动的。 第一种方法用于basic examples B1和B3a中：
下面演示了使用G4AccumulablesManager创建可累积的替代方法：
\begin{lstlisting}
// B1RunAction.hh
class B1RunAction : public G4UserRunAction
{
// ...
private:
G4Accumulable<G4double> fEdep;
G4Accumulable<G4double> fEdep2;
};
// B1RunAction.cc
B1RunAction::B1RunAction()
: G4UserRunAction(),
fEdep("Edep", 0.),
fEdep2("Edep2", 0.)	// the accumulable is initialized with a name and a value = initValue
// (the name can be omitted)
{
// ..
// Register accumulable to the accumulable manager
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance(); accumulableManager->RegisterAccumulable(fEdep);
accumulableManager->RegisterAccumulable(fEdep2);
}
\end{lstlisting}
An alternative way of creating an accumulable using G4AccumulablesManager is demonstrated below:
下面演示了使用G4AccumulablesManager创建可累积的替代方法：
\begin{lstlisting}
// B1RunAction.cc
B1RunAction::B1RunAction()
: G4UserRunAction()
{
// ..
// Accumulables can be also created via accumulable manager
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance(); accumulableManager->CreateAccumulable<G4double>("EdepBis", 0.); accumulableManager->CreateAccumulable<G4double>("Edep2Bis", 0.);
}
\end{lstlisting}
The G4AccumulablesManager takes ownership of the accumulables created by its CreateAccumulable() function the accumulables allocated in the user code has to be deleted in the user code.

Since GEANT4 10.3, the name of the accumulable can be omitted. A generic name “accumulable\_N”, where N is the current number of registered objects, will be then attributed.

In multi-threading mode all accumulables registered to G4AccumulablesManager accumulated on workers can be merged to the master thread by calling G4AccumulablesManager::Merge() function. This step may be not necessary in future after a planned closer integration of G4Accumulable classes in the GEANT4 kernel.

G4AccumulablesManager获取由其CreateAccumulable（）函数创建的累加值的所有权，用户代码中分配的累加值必须在用户代码中删除。

自从GEANT4 10.3，可累加的名称可以省略。 然后归属通用名称“accumulable\_N”，其中N是当前注册对象的数量。

在多线程模式下，可以通过调用G4AccumulablesManager :: Merge（）函数将在G4AccumulablesManager上注册的所有累积值合并到主线程中。 在GE4内核中计划将G4A累加类集成更紧密的集成之后，这一步可能不是必需的。
\begin{lstlisting}
// B1RunAction.cc
void B1RunAction::EndOfRunAction(const G4Run* run)
{
// ...
// Merge accumulables
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance();
accumulableManager->Merge();
}
The merging mode can be specified using the third (or the second one, if the name is omitted) G4Accumulable<T> constructor argument. The merge modes are defined in G4MergeMode class enumeration:
可以使用第三个（或第二个，如果名称被省略）指定合并模式。G4Accumulable <T>构造函数参数。 合并模式在G4MergeMode类的枚举中定义：

enum class G4MergeMode {
	kAddition,	// "Or" if boolean type
kMultiplication, // "And" if boolean type
 kMaximum,	// "Or" if boolean type
kMinimum	// "And" if boolean type
};
\end{lstlisting}
The default accumulable merge operation is addition.
The registered accumulables can be accessed via G4AccumulablesManager by name or by the id, attributed in the order of registering:
默认的可累积合并操作是加法。
已注册的累积值可通过G4AccumulablesManager按名称或编号访问，按注册顺序归属：
\begin{lstlisting}
// ...
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance();
// Access accumulables by name
G4double edepBis = accumulableManager->GetAccumulable<G4double>("EdepBis")->GetValue();
G4double edep2Bis = accumulableManager->GetAccumulable<G4double>("Edep2Bis")->GetValue();
// Access accumulables by id
G4VAccumulable* accumulable = accumulableManager->GetAccumulable(id);
\end{lstlisting}
\subsection{9.4.2 User defined accumulables}

Users can define their own accumulable class derived from G4VAccumulable abstract base class. An example of a ProcessCounterAccumulable class, implementing an accumulable holding a map of the processes occurrences by the processes names, is given below. Such processes occurrences map is used in several electromagnetic extended examples, e.g. TestEm1.

用户可以定义自己的可积累的类，从G4VAccumulable抽象基类派生。 下面给出了一个ProcessCounterAccumulable类的例子，它通过进程名称实现了一个可累积的进程发生的映射。 这种过程发生图用于几个电磁扩展示例中，例如TestEm1。
\begin{lstlisting}
ProcCounterAccumulable.hh:
#include "G4VAccumulable.hh"
#include "globals.hh"
#include <map>
class ProcCounterAccumulable : public G4VAccumulable
{
public:
ProcCounterAccumulable(const G4String& name)
: G4VAccumulable(name, 0), fProcCounter() {}
virtual ~ProcCounterAccumulable() {}
void CountProcesses(G4String procName);
virtual void Merge(const G4VAccumulable& other);
virtual void Reset();
private:
std::map<G4String,G4int> fProcCounter;
};
ProcCounterAccumulable.cc:
void ProcCounterAccumulable::Merge(const G4VAccumulable& other)
{
const ProcCounterAccumulable& otherProcCounterAccumulable
= static_cast<const ProcCounterAccumulable&>(other);
std::map<G4String,G4int>::const_iterator it;
for (it = otherProcCounterAccumulable.fProcCounter.begin();
it != otherProcCounterAccumulable.fProcCounter.end(); ++it) {
G4String procName = it->first;
G4int otherCount = it->second;
if ( fProcCounter.find(procName) == fProcCounter.end()){
fProcCounter[procName] = otherCount;
}
else {
fProcCounter[procName] += otherCount;
}
}
}
void ProcCounterAccumulable::Reset()
{
fProcCounter.clear();
}
\end{lstlisting}
The implementation of the CountProcesses() function is identical as in Run::CountProcesses() function in TestEm1.

在TestEm1中，CountProcesses()函数和Run::CountProcesses()函数的实现方式一样

\section{9.5 g4tools}

g4tools is a “namespace protected” part of inlib and exlib which is of some interest for GEANT4, mainly the histograms, the ntuples and the code to write them at the ROOT, HDF5, AIDA XML and CSV file formats. The idea of g4tools is to cover, with a very light and easy to install package, what is needed to do analysis in a “GEANT4 batch program”.

As g4tools is distributed through GEANT4 and in order to avoid potential namespace clashes with other codes that use the inlib/exlib to do GEANT4 visualization (as for the g4view application or some of the exlib examples), the inlib and exlib namespaces had been automatically changed to tools in the g4tools distribution. Since in principle GEANT4 users will not have to deal directly with the g4tools classes, but will manipulate histograms and ntuples

g4tools是inlib和exlib的一个“命名空间保护”部分，对GEANT4有一定的意义，主要是直方图，ntuples和用ROOT，HDF5，AIDA XML和CSV文件格式编写的代码。g4tools的想法是用一个非常简单易安装的软件包来涵盖在“GEANT4批处理程序”中进行分析所需的内容。
由于g4tools通过GEANT4分发，为了避免潜在的命名空间与使用inlib / exlib执行GEANT4可视化的其他代码（如g4view应用程序或某些exlib示例）发生冲突，inlib和exlib命名空间已自动更改到g4tools发行版中的工具。 由于原则上GEANT4用户不需要直接处理g4tools类，但会操作直方图和ntuples。


through the G4AnalysisManager, we are not going to extensively document the g4tools classes here. Interested people are encouraged to go at the inlib/exlib web pages for that (see inlib/exlib site).
通过G4AnalysisManager，我们不会在这里广泛地记录g4tools类。 我们鼓励有兴趣的人到inlib / exlib的网页上去看看inlib / exlib网站).
\subsubsection{9.5.1 g4tools package}

g4tools code is pure header

As explained in inlib/exlib, the code found in g4tools is “pure header”. This comes from the need to have an easy way to build applications, as the ioda one, from smartphone, passing by tablets and up to various desktops (UNIX and Windows). For example, if building an application targeted to the Apple AppStore and GooglePlay, the simplest way is to pass through Xcode and the Android make system (or Eclipse), and having not to build libraries simplifies a lot the handling of all these IDEs for the same application. A fallback of that is that the installation of g4tools (if not using the one coming with GEANT4) is straightforward, you simply unzip the file containing the source code! To build an application using g4tools, as for inlib/exlib, you simply have to declare to your build system the “-I” toward the unfolded directory and do “Build and Run”.

正如在inlib / exlib中所解释的，g4tools中的代码是“纯粹的头文件”。 这源于需要一种简单的方法来构建应用程序，例如智能手机，平板电脑以及各种桌面（UNIX和Windows）。 例如，如果构建一个针对Apple AppStore和GooglePlay的应用程序，最简单的方法是通过Xcode和Android make系统（或Eclipse），并且不建立库会简化大量处理所有这些IDE的同样的应用。 这样做的一个回退就是安装g4tools（如果不使用GEANT4提供的），直接解压缩包含源代码的文件即可！ 要使用g4tools构建应用程序，对于inlib / exlib，只需向构建系统声明展开目录的“-I”并执行“构建并运行”即可。

g4tools test

g4tools comes with test programs of its own that may be useful in case of problems (for example porting on a not yet covered platform). You can build and run them with:

g4tools附带了自己的测试程序，可以在出现问题时使用（例如，在尚未涵盖的平台上移植）。 您可以使用以下命令构建和运行它们
\begin{lstlisting}
UNIX> <get g4tools.zip>
UNIX> <unzip g4tools.zip>
UNIX> cd g4tools/test/cpp
UNIX> ./build
UNIX> ./tools_test_histo
UNIX> ./tools_test_wroot
UNIX> etc...
and on Windows:
DOS> <setup VisualC++ so that CL.exe is in your PATH>
DOS> <get g4tools.zip>
DOS> <unzip g4tools.zip> (you can use the unzip.exe of CYGWIN)
DOS> cd g4tools\test\cpp
DOS> .\build.bat
DOS> .\tools_test_histo.exe
DOS> .\tools_test_wroot.exe
DOS> etc...
\end{lstlisting}
\subsubsection{g4tools in GEANT4}
The g4tools header files are distributed in the GEANT4 source in the source/analysis/include/tools directory and in the GEANT4 installation, they are installed in include/tools directory. The g4tools test programs, included only in GEANT4 development versions, can be downloaded with the g4tools-[version]. zip file from the inexlib development site).

While the GEANT4 analysis manager provides the methods for booking and filling the g4tools objects, it does not interface all public functions. Users can access the g4tools objects (see Accessing Histograms) and use the g4tools API described in the next section to get the needed informations.

g4tools头文件分布在源/分析/包含/工具目录中的GEANT4源文件中，以及GEANT4安装文件中，它们安装在include / tools目录中。  g4tools测试程序仅包含在GEANT4开发版本中，可以使用g4tools- [版本]下载。  zip文件从inexlib开发网站).

虽然GEANT4分析管理器提供了用于预订和填充g4tools对象的方法，但它不会连接所有公共功能。 用户可以访问g4tools对象（请参阅访问直方图）并使用下一节中介绍的g4tools API来获取所需的信息。
\subsection{9.5.2 User API}
We describe here some of the public methods potentially seen by a user doing analysis.
我们在这里描述一些用户进行分析时可能看到的公共方法。

\subsubsection{Booking and filling}
\begin{lstlisting}
h1d(const std::string& title,unsigned int Xnumber,double Xmin,double Xmax);
 h1d(const std::string& title,const std::vector<double>& edges);
bool fill(double X,double Weight = 1);
example
#include <tools/histo/h1d>
#include <tools/randd>
 ...
tools::histo::h1d h("Gauss",100,-5,5);
tools::rgaussd rg(1,2);
for(unsigned int count=0;count<entries;count++) h.fill(rg.shoot(),1.4);
Mean and rms
tools::histo::h1d h("Gauss",100,-5,5);
 ...
std::cout << " mean " << h.mean() << ", rms " << h.rms() << std::endl;
\end{lstlisting}
\subsubsection{Bin infos}
When doing a:
\begin{lstlisting}
bool fill(double X,double Weight = 1);
\end{lstlisting}
the histogram class maintains, for each bin, the number of entries, the sum of weights that we can note “Sw”, the sum of W by W “Sw2”, the sum of X by Weight “Sxw”, the sum of X by X by W “Sx2w”. Then bin method names reflect these notations, for example to get the 50 bin sum of X*X*W:
直方图类为每个bin维护条目数，我们可以记录的权重之和“Sw”，W之和W“Sw2”，X之和权重“Sxw”，X由X乘以W“Sx2w”。 然后bin方法名称反映这些符号，例如以获得X * X * W的50个二进制总和：
\begin{lstlisting}
double Sx2w = h.bin_Sx2w(50);
\end{lstlisting}
and the same for the other sums:
对于其他求和也一样：
\begin{lstlisting}
double Sw = h.bin_Sw(50);
double Sw2 = h.bin_Sw2(50);
double Sxw = h.bin_Sxw(50);
unsigned int n = h.bin_entries(50);
\end{lstlisting}
You can have also all infos on all bins with:
您也可以在所有箱子上使用以下信息：
\begin{lstlisting}
tools::histo::h1d h(...);
...
const std::vector<unsigned int>& _entries = h.bins_entries();
const std::vector<double>& _bins_sum_w = h.bins_sum_w();
const std::vector<double>& _bins_sum_w2 = h.bins_sum_w2();
const std::vector< std::vector<double> >& _bins_sum_xw = h.bins_sum_xw();
const std::vector< std::vector<double> >& _bins_sum_x2w = h.bins_sum_x2w();
\end{lstlisting}
for example to dump bin 50 of an histo booked with 100 bins:
例如，取出以100个bins中的50个
\begin{lstlisting}
std::cout	<<	"entries[50] =	"	<<	_entries[50] << std::endl;	
std::cout	<<	" sum_w[50] =	"	<<	_bins_sum_w[50] << std::endl;	
std::cout	<<	" sum_w2[50] =	"	<<	_bins_sum_w2[50] << std::endl;	
std::cout	<<	" sum_xw[50] =	"	<<	_bins_sum_xw[50][0] << std::endl;	//0 = xaxis
std::cout	<<	"sum_x2w[50] =	"	<<	_bins_sum_x2w[50][0] << std::endl;	//0 = xaxis
\end{lstlisting}


(Take care that the [0] entries in the upper vectors are for the “underflow bin” and the last one is for the “overflow bin”).
（注意上面向量中的[0]条目是用于“下溢仓”，最后一个是“溢出仓”）。

All data
You can get all internal data of an histo through the histo\_data class:
你可以通过histo\_data类获得一个histo的所有内部数据：
\begin{lstlisting}
const tools::histo::h1d::hd_t& hdata = h.dac();	//dac=data access.
\end{lstlisting}
and then, for example, find back the bins infos with:

然后，例如，通过以下方式找回垃圾箱信息：
\begin{lstlisting}
const std::vector<unsigned int>& _entries = hdata.m_bin_entries;
const std::vector<double>& _bins_sum_w = hdata.m_bin_Sw;
const std::vector<double>& _bins_sum_w2 = hdata.m_bin_Sw2;
const std::vector< std::vector<double> >& _bins_sum_xw = hdata.m_bin_Sxw;
 const std::vector< std::vector<double> >& _bins_sum_x2w = hdata.m_bin_Sx2w;
// dump bin 50 :
std::cout << "entries[50] = " << _entries[50] << std::endl;
std::cout << " sum_w[50] = " << _bins_sum_w[50] << std::endl;
std::cout << " sum_w2[50] = " << _bins_sum_w2[50] << std::endl;
std::cout << " sum_xw[50] = " << _bins_sum_xw[50][0] << std::endl;	//0 = xaxis
std::cout << "sum_x2w[50] = " << _bins_sum_x2w[50][0] << std::endl; //0 = xaxis
\end{lstlisting}
See the tools/histo/histo\_data class for all internal fields.
查看所有内部字段的tools / histo / histo\_data类。

Projections

From a 2D histo, you can get the x projection with:

从2D histo中，您可以获得x投影：

\begin{lstlisting}
tools::histo::h1d* projection = tools::histo::projection_x(h2d,"ProjX");
...
delete projection;
\end{lstlisting}
See test/cpp/histo.cpp for example code. Other slicing and projection methods are:
示例代码参见test/cpp/histo.cpp 其他切片和投影方法是：
\begin{lstlisting}
// h2d -> h1d. (User gets ownership of the returned object).
h1d* slice_x(const h2d&,int y_beg_ibin,int y_end_ibin,const std::string& title);
h1d* projection_x(const h2d&,const std::string& title);
h1d* slice_y(const h2d&,int x_beg_ibin,int x_end_ibin,const std::string& title);
h1d* projection_y(const h2d&,const std::string& title);
// h2d -> p1d. (User gets ownership of the returned object).
p1d* profile_x(const h2d&,int y_beg_ibin,int y_end_ibin,const std::string& title);
p1d* profile_x(const h2d&,const std::string&);
p1d* profile_y(const h2d&,int x_beg_ibin,int x_end_ibin,const std::string& title);
p1d* profile_y(const h2d&,const std::string& title);
// h3d -> h2d. (User gets ownership of the returned object).
h2d* slice_xy(const h3d&,int z_beg_ibin,int z_end_ibin,const std::string& title);
h2d* projection_xy(const h3d&,const std::string& title);
h2d* slice_yz(const h3d&,int x_beg_ibin,int x_end_ibin,const std::string& title);
 h2d* projection_yz(const h3d&,const std::string& title);
h2d* slice_xz(const h3d&,int y_beg_ibin,int y_end_ibin,const std::string& title);
h2d* projection_xz(const h3d&,const std::string& title);
\end{lstlisting}
